import { PersonDto, PersonService } from '@proxy/people';
import {
  Component,
  EventEmitter,
  inject,
  Input,
  OnChanges,
  Output,
  SimpleChanges,
} from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-person-edit-modal',
  templateUrl: './person-edit-modal.component.html',
  styleUrl: './person-edit-modal.component.scss',
})
export class PersonEditModalComponent implements OnChanges {
  @Input() visible = false;
  @Input() person?: PersonDto;
  @Output() visibleChange = new EventEmitter<boolean>();
  @Output() saved = new EventEmitter();

  private _personService = inject(PersonService);

  private _fb = inject(FormBuilder);
  form = this.createForm();

  ngOnChanges(changes: SimpleChanges): void {
    const { person } = changes;
    if (person) {
      this.form = this.createForm(person.currentValue);
    }
  }

  createForm(person?: PersonDto) {
    return this._fb.group({
      personName: [person?.personName, Validators.required],
      idNumber: [person?.idNumber, Validators.required],
      sex: [person?.sex],
      personType: [person?.personType],
      personCode: [person?.personCode],
    });
  }

  save() {
    this._personService.create(this.form.value).subscribe(() => {
      this.saved.emit();
      this.visibleChange.emit(false);
    });
  }
}
